<template>
  <div>
    <el-container class="e-container">
      <!-- 左侧订单产品列表面板 -->
      <el-container>
        <el-header class="el-header" style="height: 160px">
          <span>订单列表</span>
        </el-header>
        <el-main class="e-main">
          <el-table :data="tableData" style="font-size: 18px">
            <el-table-column prop="name" label="产品名称"> </el-table-column>
            <el-table-column prop="price" label="产品单价" width="200">
            </el-table-column>
            <el-table-column prop="count" label="产品数量" width="150">
            </el-table-column>
            <el-table-column prop="totalprice" label="产品小结" width="300">
            </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button
                  class="edit_btn"
                  @click.native.prevent="editHandle(scope.$index, scope.row)"
                  type="success"
                  >编辑</el-button
                >
                <el-button
                  class="remove_btn"
                  @click.native.prevent="removeList(scope.$index, tableData)"
                  type="success"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
      <!-- 右侧订单结算面板 -->
      <el-aside class="aside" style="width: 400px">
        <el-row>
          <!-- 摄像头展示位置 -->
          <steambarcodereader
            @decode="addList"
            width="400px"
            height="400px"
          ></steambarcodereader>
        </el-row>
        <el-row class="order_panel">
          <el-row class="order_text">
            <!-- 小计统计面板 -->
            <el-row class="e_row">
              <el-col :span="12">产品件数：</el-col>
              <el-col :span="12">{{ sum }}件</el-col>
            </el-row>
            <el-row class="e_row">
              <el-col :span="12">总价格：</el-col>
              <el-col :span="12">￥{{ total_price }}元</el-col>
            </el-row>
          </el-row>
          <el-row>
            <div>
              <!-- 结算按钮 -->
              <el-button
                icon="el-icon-s-goods"
                @click="toOrder"
                class="order_btn"
                type="success"
                :disabled="isOrderButtonActive"
                >下单结算</el-button
              >
              <el-button class="hidden" v-trigger>xx</el-button>
            </div>
          </el-row>
        </el-row>
      </el-aside>
    </el-container>
    <!-- 进入该页面提示音 -->
    <welcomeAudioTip
      :audiourl="welcomeAudioTipurl"
      ref="child"
    ></welcomeAudioTip>
    <!-- 编辑框-->
    <el-dialog
      title="编辑产品数量"
      :visible.sync="editDialogVisible"
      width="30%"
    >
      <el-form ref="form" :model="form" label-width="70px">
        <el-input-number
          v-model="form.count"
          :precision="0"
          :step="1"
          :min="1"
          :max="100"
          label="产品数量"
        ></el-input-number>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveEdit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  <script>
//引用视频扫描组件
import steambarcodereader from "@/components/steambarcodereader.vue";
import welcomeAudioTip from "@/components/welcomeAudioTip.vue";

export default {
  name: "orderList",
  components: {
    steambarcodereader,
    welcomeAudioTip,
  },
  directives: {
    //自动触发交互
    trigger: {
      inserted(el, binging) {
        el.click();
      },
    },
  },
  data() {
    return {
      tableData: [], //订单的产品列表信息
      image: 'require("@/assets/img/img01.jpg")',
      barcode: "",
      sum: 0, //商品总数
      total_price: 0, //商品总价
      welcomeAudioTipurl: require("@/assets/media/goinorder.mp3"), //初始化欢迎提示音
      editDialogVisible: false,
      form: {},
      isOrderButtonActive: true,
    };
  },
  mounted() {
    this.welcomeAudioTip();
  },
  methods: {
    welcomeAudioTip() {
      this.welcomeAudioTipurl = require("@/assets/media/goinorder.mp3");
      this.$refs.child.play();
    },
    toOrder() {
      //下单结算并将订单列表数据传递到结算页面
      // this.$router.push("./payment");
      //带参数传递的语法格式
      this.$router.push({
        path: "/payment",
        name: "PaymentView",
        params: {
          orderList: this.tableData,
          sum: this.sum,
          totalPrice: this.total_price,
        },
      });
    },
    //扫码方法
    async addList(barcode) {
      //通过子组件扫码获得商品信息，并加入到当前组件中
      //这里的data数据来自子组件
      //增加商品进入列表

      var res = await this.$http.post("postProductByBarcode", {
        barcode: barcode,
      });
      //console.log(res);
      //将res里data（产品信息）
      var productData = res.data;
      //如果没有产品返回空值
      if (productData == null) {
        return;
      }
      //这里做判断，如果产品已经存在于tableData，则产品的num+1,否则push新数据

      var newproduct = {
        id: productData.id,
        barcode: productData.barcode,
        name: productData.name,
        price: productData.price,
        totalprice: productData.price,
        count: 1,
      };

      let table = this.tableData;
      //使用map对数组对象循环遍历，判断循环项是否和新产品barcode相等
      //如果相等则产品数量+1 ，否则向数组中push新对象
      if (table.some((table) => table.barcode === newproduct.barcode)) {
        this.tableData.map(function (item) {
          if (item.barcode == newproduct.barcode) {
            item.count += 1;
            //价格小结累加
            item.totalprice = (
              parseFloat(item.totalprice) + parseFloat(newproduct.price)
            ).toFixed(2);
          }
        });
      } else {
        this.tableData.push(newproduct);
      }

      

      //更新表格
      this.updataOrder(this.tableData);
    },
    //更新订单
    updataOrder(data) {      

      //计算产品总数
      this.sum = 0;
      for (let i = 0; i < data.length; i++) {
        this.sum += data[i].count;
      }
      //循环变量tabelData数据的小结价格字段并进行计算汇总
      var price = 0.0;
      for (let i = 0; i < data.length; i++) {
        price = this.addPrice(price, data[i].totalprice);
      }
      this.total_price = price;

      //如果表格数据为空，则下单按钮不可用
      if (this.tableData.length!=0) {
        this.isOrderButtonActive = false;
      }else{
        this.isOrderButtonActive = true;
      }
    },
    //价格计算方法1
    addPrice(data1, data2) {
      // 加法
      let r1, r2, m;
      // 获取每个参数的小数的位数
      try {
        r1 = data1.toString().split(".")[1].length;
      } catch (e) {
        r1 = 0;
      }
      try {
        r2 = data2.toString().split(".")[1].length;
      } catch (e) {
        r2 = 0;
      }
      // 计算底数为10以最大小数位数为次幂的值
      m = Math.pow(100, Math.max(r1, r2));
      // 把所有参数转为整数后相加再除以次幂的值
      return (data1 * m + data2 * m) / m;
    },
    removeList(index, rows) {
      this.$confirm("确定删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          rows.splice(index, 1);
          //只要对产品列表内数据进行操作，就要更新一次产品数量和小计
          this.updataOrder(this.tableData);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //点击编辑按钮
    editHandle(index, rows) {
      this.editDialogVisible = true;
      console.log(rows);
      this.form = rows;
    },
    saveEdit() {
      let rows = this.form;
      rows.totalprice = (parseFloat(rows.price) * rows.count).toFixed(2);
      //更新价格
      this.$message({
        type: "success",
        message: "编辑成功",
      });
      this.updataOrder(this.tableData);
      this.editDialogVisible = false;
    },
  },
};
</script>
<style type="css" scoped>
.e-container {
  height: 900px;
  border: 1px solid #eee;
}

.e-main {
  overflow: auto;
  overflow-y: scroll;
}

.e-container .el-header {
  background-color: #409eff;
  color: #fff;
  line-height: 160px;
  font-size: 30px;
}

.el-aside {
  position: relative;
  color: #000;
}

.aside {
  position: relative;
  width: 400px;
  background-color: #fff;
  overflow: hidden;
  text-align: center;
}
.order_panel {
  position: absolute;
  bottom: 0px;
}
.order_text {
  font-weight: 500;
  font-size: 30px;
  width: 400px;
}

.e_row {
  height: 100px;
}

.remove_btn {
  width: 150px;
  height: 60px;
}

.edit_btn {
  width: 150px;
  height: 60px;
  color: #fff;
}

.order_btn {
  width: 400px;
  height: 200px;
  font-size: 40px;
  color: #fff;
}

.hidden {
  display: none;
}
</style>